package app.controllers.admin.wx;

import app.Const;
import app.models.DaoKit;
import app.models.wx.MessageSetting;
import app.wxchat.WxChatMessageHelper;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.collect.Lists;
import com.jfinal.log.Logger;
import com.jfinal.module.wxchat.core.Constants;
import com.jfinal.module.wxchat.message.OutputMessage;
import com.jfinal.module.wxchat.message.output.Item;
import com.jfinal.module.wxchat.message.output.NewsOutputMessage;
import com.jfinal.module.wxchat.message.output.TextOutputMessage;
import com.jfinal.module.wxchat.utils.MessageUtil;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
public class MessageController extends BasicController {
    Logger logger = Logger.getLogger(MessageController.class);

    private void parseMessage(MessageSetting messageSetting) {
        Object id = null;
        String type = Constants.MSGTYPE_NEWS;
        OutputMessage message;
        if (messageSetting != null) {
            boolean messageType = messageSetting.getBoolean("message_type");
            Class<? extends OutputMessage> clz = null;
            if (!messageType) {
                type = Constants.MSGTYPE_NEWS;
                clz = NewsOutputMessage.class;
            } else {
                type = Constants.MSGTYPE_TEXT;
                clz = TextOutputMessage.class;
            }
            id = messageSetting.get("id");
            String content = messageSetting.getStr("content");
            logger.debug(content);
            message = MessageUtil.xmlToOutputMessage(content, clz);
        } else {
            NewsOutputMessage news = new NewsOutputMessage.Builder("", "", 0l, "").build();
            List<Item> items = Lists.newArrayList(new Item("", "", "", ""));
            news.setArticles(items);
            message = news;
        }
        setAttr("id", id);
        setAttr("message_type", type);
        setAttr("message", message);

    }

    public void welcome() {
        setAttr("_title_", "自定义欢迎词");
        setAttr("_small_", "设置关注时显示信息");
        setAttr("_li2_", "自定义欢迎词");
        setAttr("_head_", "欢迎词信息");
        setAttr("register", "true");

        MessageSetting messageSetting = MessageSetting.dao.subscribe();
        parseMessage(messageSetting); //解析消息

        render("item.ftl");
    }

    public void replayEdit() {
        setReplyTips();
        MessageSetting aMessageSetting = MessageSetting.dao.findById(getPara());
        parseMessage(aMessageSetting); //解析消息

        setAttr("keyword", aMessageSetting.get("keyword"));

        render("item.ftl");
    }

    public void reply() {
        render("replyindex.ftl");
    }

    public void replyList() {
        final DatatablesCriterias criterias = getCriterias();
        Page<MessageSetting> page = MessageSetting.dao.datatable(criterias);

        renderDataTables(page, criterias);
    }

    public void replayRemove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("messagesetting.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

    public void replyCreate() {
        setReplyTips();

        parseMessage(null);

        render("item.ftl");
    }

    private void setReplyTips() {
        setAttr("_title_", "自定义回复内容");
        setAttr("_small_", "设置自定义回复消息信息");
        setAttr("_li2_", "自定义回复内容");
        setAttr("_head_", "回复信息");
        setAttr("register", "false");
    }

    public void save() {
        try {
            List<UploadFile> files = getFiles();

            boolean register = getParaToBoolean("register", false);
            //boolean click = getParaToBoolean("click", false);
            String keyword = getPara("keyword");

            int id = getParaToInt("id", 0);
            String messageType = getPara("message_type");
            Enumeration<String> paraNames = getParaNames();
            OutputMessage message = new WxChatMessageHelper().convert(messageType, files, paraNames, getRequest());

            String content = MessageUtil.outputMessageToXml(message);

            MessageSetting messageSetting = new MessageSetting();
            messageSetting.set("message_type", (Constants.MSGTYPE_TEXT.equals(messageType) ? true : false));
            messageSetting.set("content", content);
            messageSetting.set("type", "0");
            messageSetting.set("register", register);
            messageSetting.set("keyword", keyword);

            if (id == 0) {
                messageSetting.set("click", false);
                messageSetting.set("create_time", new Date());
                messageSetting.save();
            } else {
                messageSetting.set("id", id);
                messageSetting.update();
            }

            if (register) {
                setAttr("_title_", "自定义欢迎词");
                setAttr("_small_", "设置关注时显示信息");
                setAttr("_li2_", "自定义欢迎词");
                setAttr("_head_", "欢迎词信息");
                setAttr("register", "true");
            } else {
                setAttr("_title_", "自定义回复内容");
                setAttr("_small_", "设置自定义回复消息信息");
                setAttr("_li2_", "自定义回复内容");
                setAttr("_head_", "回复信息");
                setAttr("register", "false");

                setAttr("keyword", keyword);
            }

            setAttr("id", messageSetting.get("id"));
            setAttr("message_type", messageType);
            setAttr("message", message);

            setAttr("ok_message", "保存成功");
        } catch (Exception e) {
            setAttr("error_message", "保存失败");
        }
        render("item.ftl");
    }


}
